import ConfigParser, re
import logst.parsers_base as parsers_base

class simple_Parser(parsers_base.base_Parser_class):

   default_icon = "images/32px-Crystal_Clear_app_kcmdf.png"

   description = "This plugin reads its configuration from a plain text-file and uses regular expressions to generate events"

   def initialize(self):

      self.config = ConfigParser.ConfigParser()

      self.config.read([ self.global_config["confdir"] + '/simple_parser.rules', self.global_config["confdir"] + '/simple_parser.local'])

      for section in self.config.sections():

         if self.config.has_option(section, "regex"):

            enabled = True

            if self.config.has_option(section, "default_off"):
               enabled = not self.config.getboolean(section, "default_off")

            entry_regex = self.config.get(section, "regex")

            if self.config.has_option(section, "description"):
               description = self.config.get(section, "description")
            else:
               description = section

            self.add_option(hash(entry_regex), description, default_value = enabled)

   def init_activators(self):

      for section in self.config.sections():

         if self.config.has_option(section, "regex"):

            entry_regex = self.config.get(section, "regex")
            optname = hash(entry_regex)

            if self.get_option(optname).is_true():
               self.add_regex_activator(entry_regex, self.parse_line)

   def parse_line(self, log):

      for section in self.config.sections():
         match = False

         if self.config.has_option(section, "daemon") and log.daemon() != self.config.get(section, "daemon"):
            continue

         if self.config.has_option(section, "find"):
            if log.line.find(self.config.get(section, "find")) >= 0:
               match = True
         elif self.config.has_option(section, "regex"):

            if section.find("%s") >= 0 and self.config.get(section, "regex").find("(.+)") >= 0:
               # regex contains
               found = re.findall(self.config.get(section, "regex"), log.message())
               if found:
                  found = found[0]
                  event_txt = section % found
                  match = True
            else:
               if re.match(".*%s" % self.config.get(section, "regex"), log.line):
                  event_txt = section
                  match = True

         if not match:
            continue

         if self.config.has_option(section, "icon"):
            icon = self.config.get(section, "icon")
         else:
            icon = None # means that self.default_icon will be used

         self.add_event(log, text = event_txt, icon = icon)

      return None
